/*************************************************************************
* Title: The Key driver Inteface Implementation  File
* 
* File:  key.c 
* Author: lvyi
*
* Discription: This file contains key driver  function

**************************************************************************/

#include "board.h"
#include "key.h"
#include "timer.h"
unsigned char keyValueBoard;

static U16 KeyScan_Timer;

void keyboard_init(void)
{  
	DDRC |= 0x70;
	DDRC &= 0xF0;
	KeyScan_Timer = Timer_GetTickCount();
}


static unsigned char keyboardScan(void)
{	
	static unsigned char key_state = 0, key_value, key_line;
    unsigned char key_return = No_key,i;
	
	switch (key_state)
	{
		case 0:
			key_line = 0b01000000;
			for (i=0; i<3; i++)			// 扫描键盘
			{	
				PORTC = 0x7F&(~key_line);			// 输出行线电平
				PORTC = 0x7F&(~key_line);			// 必须送2次！！！
                key_value = Key_mask & PINC;// 读列电平
				if (key_value == Key_mask)
					key_line >>= 1;			// 没有按键，继续扫描
				else
				{
					key_state++;			// 有按键，停止扫描
					break;					// 转消抖确认状态
				}
			}
			break;
		case 1:
			if (key_value == (Key_mask & PINC))	// 再次读列电平，
			{
				key_return = 0x7F&(key_line | key_value);// 与状态0的相同，确认按键				
				key_state++;				 // 转入等待按键释放状态
			}
			else
				key_state--;				 // 两次列电平不同返回状态0，（消抖处理）
			break;						
		case 2:							     // 等待按键释放状态
			PORTC = 0b00001111;			     // 行线全部输出低电平
			PORTC = 0b00001111;			     // 重复送一次
			if ( (Key_mask & PINC) == Key_mask)
				key_state=0;				 // 列线全部为高电平返回状态0
			break;
	}
	return key_return;
}



unsigned char keyBoard_read(void)
{
	volatile uint8_t temp = keyValueBoard;
	keyValueBoard = No_key;
	return temp;

}


//--------------------------------------------------
// Scan the keyboard and response the key
//
void keyBoard_process(void)
{
	if(Timer_PassedDelay(KeyScan_Timer, 10)) 
	{		
		KeyScan_Timer = Timer_GetTickCount();
		keyValueBoard = keyboardScan();
	}
}

